package com.zn.web.rpc;

import com.alibaba.fastjson.JSONObject;
import com.zn.util.Constant;
import com.zn.util.EnDecryptUtil;
import com.zn.util.HttpClientUtil;
import com.zn.vo.Response;
import com.zn.web.dto.VerifyDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by yinji on 2018/8/9.
 */
@Component
public class PayRemoteCall {
    private static final Logger LOGGER = LoggerFactory.getLogger(PayRemoteCall.class);
    @Value("${zhifuqiao.url}")
    private String url;
    @Value("${zhifuqiao.mchid}")
    private String mchid;
    @Value("${zhifuqiao.sign.key}")
    private String key;
    @Value("${zhifuqiao.interface.getaction}")
    private String getAction;
    @Value("${zhifuqiao.interface.quick.verify}")
    private String quickVerify;
    @Value("${zhifuqiao.interface.gateway.verify}")
    private String gatewayVerify;
    @Value("${zhifuqiao.interface.dfquery}")
    private String dfQuery;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     *获取支付通道
     * @param payType
     * @return
     */
    public Response getActionMethod(String payType){
        Response response = HttpClientUtil.post(url,
                HttpClientUtil.Builder.builder(getAction)
                        .with("mch_id", mchid)
                        .with("pay_method", payType)
        );
        return response;
    }

    /**
     * 支付接口 - 充值
     * @param tradeNo 订单号 15位以上字符串(规则yyyyMMddHHmmss+Math.random(4))
     * @param money 金额
     * @param uid 用户标识 用户在平台唯一标识(customerId)
     * @param action 支付通道-通过获取支付通道接口获取后回传id
     * @param payMethod 支付方式 1网关 2快捷
     * @return 返回结果
     */
    public Response verifyMethod1(String tradeNo,Double money,String uid,String action,Integer payMethod){
        String moneyStr = money.toString().replaceAll("0+?$", "");//去掉后面无用的零
        moneyStr = moneyStr.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点
        String signStr="action="+action+"&currency=CNY&mch_id="+mchid+
                "&money="+moneyStr+"&pay_method="+payMethod+"&trade_no="+tradeNo+"&uid="+uid+"&key="+key;
        LOGGER.info("signStr:"+signStr);
        String interfaceName=payMethod==1?gatewayVerify:quickVerify;
        String sign=EnDecryptUtil.MD5(signStr).toUpperCase();
        Response response = HttpClientUtil.post(url,
                HttpClientUtil.Builder.builder(interfaceName)
                        .with("mch_id", mchid)
                        .with("trade_no", tradeNo)
                        .with("money", money)
                        .with("currency", "CNY")
                        .with("uid", uid)
                        .with("action", action)
                        .with("pay_method", payMethod)
                        .with("sign", sign)
        );
        return response;
    }

    /**
     * 支付接口 - 充值
     * @param verifyDto
     * @return
     */
    public Response verifyMethod(VerifyDto verifyDto){
        String moneyStr = verifyDto.getMoney().toString().replaceAll("0+?$", "");//去掉后面无用的零
        moneyStr = moneyStr.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点
        String signStr="action="+verifyDto.getAction()+"&bank_code="+verifyDto.getBankCode()+"&branches="+verifyDto.getBranches()
                +"&card_no="+verifyDto.getCardNo()+"&cert_type=1&currency=CNY&mch_id="+mchid+"&money="+moneyStr+"&name="+verifyDto.getName()
                +"&number_id="+verifyDto.getNumberId()+"&pay_method="+verifyDto.getPayMethod()+"&tel="+verifyDto.getTel()+"&trade_no="+verifyDto.getTradeNo()
                +"&uid="+verifyDto.getUid()+"&Key="+key;
//        String signStr="action=61&bank_code=CCB&branches=杨浦支行&card_no=6214832155831139&cert_type=1&currency=CNY&mch_id=18081717226000&money=100.6&name=蒋俊勇&number_id=41270219890629841X&pay_method=1&tel=15225777187&trade_no=201812171344505098&uid=9411&Key=5f94cff8eda6e1596fbb9b6f763810ce";
        LOGGER.info("signStr:"+signStr);
        String interfaceName=verifyDto.getPayMethod()==1?gatewayVerify:quickVerify;
        /**验签数据拼接完成后转大写MD5加密后大写提交**/
        String sign=EnDecryptUtil.MD5(signStr.toUpperCase()).toUpperCase();
        Response response = HttpClientUtil.post(url,
                HttpClientUtil.Builder.builder(quickVerify)
                        .with("action", verifyDto.getAction())
                        .with("bank_code", verifyDto.getBankCode())
                        .with("branches", verifyDto.getBranches())
                        .with("card_no", verifyDto.getCardNo())
                        .with("cert_type", 1)
                        .with("currency", "CNY")
                        .with("mch_id", mchid)
                        .with("money", verifyDto.getMoney())
                        .with("name", verifyDto.getName())
                        .with("number_id", verifyDto.getNumberId())
                        .with("pay_method", verifyDto.getPayMethod())
                        .with("tel", verifyDto.getTel())
                        .with("trade_no", verifyDto.getTradeNo())
                        .with("uid", verifyDto.getUid())
                        .with("sign", sign)
        );
        return response;
    }

    /**
     *代付查询接口
     * @param tradeNo
     * @return
     */
    public Response dfQueryMethod(String tradeNo){
        String signStr="mch_id="+mchid+"&trade_no="+tradeNo+"&key="+key;
        String sign=EnDecryptUtil.MD5(signStr).toUpperCase();
        Response response = HttpClientUtil.post(url,
                HttpClientUtil.Builder.builder(dfQuery)
                        .with("mch_id", mchid)
                        .with("trade_no", tradeNo)
                        .with("sign", sign)
        );
        return response;
    }

    /**
     * 资金记录发布到crm
     * @param serviceId 业务ID
     * @param serviceType 业务类型 0出金，1报单，2开仓，3平仓，4线上入金，5代付出金 6报单撤单
     * @param operationCapital 操作资金
     * @param operationFreezeCapital 操作冻结资金
     */
    public void sendCashFlowToCrm(String serviceId,Integer serviceType,Double operationCapital,Double operationFreezeCapital){
        try {
            LOGGER.info("param--->"+serviceId+"|"+serviceType+"|"+operationCapital+"|"+operationFreezeCapital);
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("id",serviceId);
            map.put("type", serviceType);
            map.put("operationCapital", operationCapital);
            map.put("operationFreezeCapital", operationFreezeCapital);
            Object json= JSONObject.toJSON(map);
            LOGGER.info("sendCashFlowToCrm............info:"+json.toString());
            redisTemplate.convertAndSend(Constant.FUTURE_CUSTOMER_FLOW, json.toString());
        }catch (Exception e){
            LOGGER.error("sendCashFlowToCrmError...........",e);
        }
    }
}
